import {
    Button, Chip, Input,
    Modal,
    ModalBody,
    ModalContent,
    ModalFooter,
    ModalHeader,
    Textarea,
    useDisclosure
} from "@nextui-org/react";
import React, {CSSProperties, useEffect, useState} from "react";
import NoteContent from "@/app/service/noteContent";
import {MdEditor, MdPreview, ToolbarTips} from 'md-editor-rt';
import 'md-editor-rt/lib/style.css';
import PubSub from "pubsub-js"

import UpdateNote from "@/app/service/UpdateNote";
import {decodeFromBase64} from "next/dist/build/webpack/loaders/utils";
import UploadFileService from "@/app/service/UploadFileService";
import EmojiSelect from "@/app/components/tools/EmojiSelect";
import theme from "tailwindcss/defaultTheme";
import {useTheme} from "next-themes";
/*编辑器*/
/**
 * 更新笔记内容组件
 * @param isOpen
 * @param onOpenChange
 * @param noteId
 * @param folderId
 * @constructor
 */
export default function NoteEdit({isOpen, onOpenChange, noteId, folderId}: any) {
    /*获取的数据 -- 标题*/
    const [title, setTitle] = useState('');
    /*获取的数据 -- 内容*/
    const [content, setContent] = useState('');
    /*编辑器实时更新内容 -- 内容*/
    const [editorValue, setEditorValue] = useState('');
    /*获取的数据 -- Emoji*/
    const [emoji, setEmoji] = useState('📄');
    /*选择表情*/
    const {isOpen: isSelectEmoji, onOpen: onOpenSelectEmoji, onOpenChange: onSelectChange} = useDisclosure()
    /*编辑器状态栏*/
    const [toolbars] = useState<(keyof ToolbarTips)[] | undefined>(
        [
            'save', /*底部按钮保存 */
            'bold',
            'underline',
            'italic',
            '-',
            'strikeThrough',
            'title',
            'sub',
            'sup',
            'quote',
            'unorderedList',
            'orderedList',
            '-',
            'codeRow',
            'code',
            'link',
            'image',
            'task',
            '-',
            'table',
            'mermaid',
            'katex',
            '-',
            'revoke',
            'next',
            '=',
            'pageFullscreen',
            'preview',
            'htmlPreview',
            'prettier',
            'catalog'
        ],
    );

    /**
     * 主题切换
     */
    const {theme, setTheme} = useTheme()

    /*获取笔记数据*/
    async function fetchData() {
        const data = await NoteContent(noteId);
        if (!data.content) {
            return;
        }
        setTitle(data.title);
        setEmoji(data.icon)
        /*setContent(data.content) 直接使用setEditorValue 其实一样的 */
        setEditorValue(decodeFromBase64(data.content));
    }

    /*当笔记id变化就重新拉取*/
    useEffect(() => {
        fetchData().then(r => {
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [noteId]);

    return (
        <>
            <Modal
                size={'full'}
                isOpen={isOpen}
                onClose={() => {
                    /* 由于id没变化无法获取 setEditorValue('')*/
                }}
                onOpenChange={onOpenChange}
                backdrop={"blur"}
                isDismissable={false}
                radius={"lg"}
                placement={"auto"}
                scrollBehavior={"inside"}
                className={'h-full'}
            >
                <ModalContent>
                    {(onClose) => (
                        <>
                            <ModalHeader className="flex flex-col gap-1 dark:text-white light:text-black ">编 辑 笔 记</ModalHeader>
                            <ModalBody>
                                <div className={'flex text-center items-center'}>
                                    {/*Icon*/}
                                    <div className={'flex text-center justify-center items-center pe-3'}>
                                        <p className={`text-3xl shadow border rounded-md pt-0.5 pb-0.5`}
                                           onClick={(v) => {
                                               onOpenSelectEmoji()
                                           }}>{emoji}</p>
                                    </div>
                                    {/*标题*/}
                                    <Input
                                        size={'sm'}
                                        fullWidth={true}
                                        variant="bordered"
                                        value={title}
                                        className="w-full dark:text-white light:text-black "
                                        onValueChange={setTitle}
                                    />
                                </div>
                                {/*内容*/}
                                <MdEditor className={'rounded-lg'} modelValue={editorValue}
                                          onChange={setEditorValue}
                                          toolbars={toolbars}
                                          style={
                                              {
                                                  height: '100%'
                                              } as React.CSSProperties
                                          }
                                          showCodeRowNumber={true}
                                          noUploadImg={false}
                                          autoDetectCode={true}
                                          theme={theme == 'light' ? 'light' : 'dark'}
                                          showToolbarName
                                          onSave={() => {/*保存事件 小图标有效 还有快捷键*/
                                              /*更新笔记*/
                                              UpdateNote({
                                                  folderId,
                                                  noteId,
                                                  title,
                                                  editorValue,
                                                  emoji
                                              }).then(r => {
                                              });
                                          }}
                                          preview={true}
                                          onUploadImg={(files, callback) => {
                                              UploadFileService(files, callback).then(r => {
                                              })
                                          }}
                                    /*onHtmlChanged={(h) => {console.log(h)}}*/
                                />
                            </ModalBody>
                            <ModalFooter>
                                <Button size={"md"} color="danger" variant="light" onPress={() => {
                                    onClose()
                                }}>
                                    取 消
                                </Button>
                                <Button size={"md"} color="primary" onClick={() => {
                                    /*更新笔记*/
                                    UpdateNote({folderId, noteId, title, editorValue, emoji}).then(r => {
                                    });
                                }}>
                                    保 存
                                </Button>
                            </ModalFooter>
                        </>
                    )}
                </ModalContent>
            </Modal>
            {/*表情选择*/}
            <EmojiSelect isSelect={isSelectEmoji} onSelectChange={onSelectChange} setEmoji={setEmoji}/>
        </>
    )
}